package com.korion.kdyassistant.ui

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.Window
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import com.blankj.utilcode.util.AppUtils
import com.korion.kdyassistant.R
import com.korion.kdyassistant.base.ControlService
import com.korion.kdyassistant.databinding.ActivityAutoClickBinding
import com.korion.kdyassistant.utils.PermissionUtils
import com.korion.kdyassistant.utils.showToast

class AutoClickActivity : AppCompatActivity(), View.OnClickListener {
    companion object {
        const val TAG = "AutoClickActivity"
        const val KEY_TIME = "time"
        const val KEY_INTERVAL = "interval"
        const val KEY_ENABLE_RANDOM = "enable_random"
        const val KEY_RANDOM_MIN = "random_min"
        const val KEY_RANDOM_MAX = "random_max"
    }

    private var mCount = 0
    private var currentPkg: AppUtils.AppInfo? = null

    private lateinit var binding: ActivityAutoClickBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
        window.statusBarColor = getColor(R.color.transparent)

        binding = ActivityAutoClickBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        binding.btnLaunch.setOnClickListener(this)
        binding.tvCount.setOnClickListener(this)

        val sp = getPreferences(Context.MODE_PRIVATE)
        val time = sp.getInt(KEY_TIME, 1800)
        val interval = sp.getInt(KEY_INTERVAL, 6000)
        val enableRandom = sp.getBoolean(KEY_ENABLE_RANDOM, false)
        val min = sp.getInt(KEY_RANDOM_MIN, 0)
        val max = sp.getInt(KEY_RANDOM_MAX, 0)

        binding.edtPeriod.setText(time.toString())
        binding.edtInterval.setText(interval.toString())
        binding.swRandom.isChecked = enableRandom
        binding.edtRandomMax.setText(max.toString())
        binding.edtRandomMin.setText(min.toString())

        binding.spinnerPackage.apply {
            val appsInfo = AppUtils.getAppsInfo()
            val appsInfoWrapper = mutableListOf<AppInfoWrapper>()
            this.onItemSelectedListener = object : OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    currentPkg = appsInfoWrapper[position].appinfo
                    Log.d(TAG, "current package: $currentPkg")
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
//                desc.text = ""
                }
            }
            for (appinfo in appsInfo) {
                if (!appinfo.isSystem && appinfo.packageName != packageName) {
                    appsInfoWrapper.add(AppInfoWrapper(appinfo))
                }
            }
            this.adapter = ArrayAdapter(this@AutoClickActivity,
                R.layout.item_spinner, R.id.tv_item, appsInfoWrapper)
        }
    }

    override fun onClick(view: View) {
        when(view.id){
            R.id.btn_launch -> {
                if (PermissionUtils.checkSystemWindowPermission(this)
                    && PermissionUtils.checkAccessibilityService(this)){
                    val period: Int
                    val interval: Int
                    var min = 0
                    var max = 0
                    val enableRandom = binding.swRandom.isChecked
                    try {
                        period = binding.edtPeriod.text.toString().toInt() * 1000
                        interval = binding.edtInterval.text.toString().toInt()
                        if (enableRandom){
                            min = binding.edtRandomMin.text.toString().toInt()
                            max = binding.edtRandomMax.text.toString().toInt()
                        }
                    } catch (e: NumberFormatException){
                        showToast("输入数值有误")
                        return
                    }
                    val sp = getPreferences(Context.MODE_PRIVATE)
                    sp.edit().putInt(KEY_TIME, period/1000)
                        .putInt(KEY_INTERVAL, interval)
                        .putBoolean(KEY_ENABLE_RANDOM, enableRandom)
                        .putInt(KEY_RANDOM_MAX, max)
                        .putInt(KEY_RANDOM_MIN, min)
                        .apply()
                    //启动服务
                    val intent = Intent(this, ControlService::class.java)
                    intent.putExtra(ControlService.KEY_PERIOD, period)
                    intent.putExtra(ControlService.KEY_INTERVAL, interval)
                    intent.putExtra(ControlService.KEY_RADMON_MAX, max)
                    intent.putExtra(ControlService.KEY_RADMON_MIN, min)
                    startService(intent)
                    currentPkg?.run {
                        launchReaderActivity(this)
                        finish()
                    }
                } else {
                    showToast("需配置权限")
                }
            }
            R.id.tv_count -> {
                mCount++
                binding.tvCount.text = mCount.toString()
            }
        }
    }

    private fun launchReaderActivity(appInfo: AppUtils.AppInfo){
        val intent = packageManager.getLaunchIntentForPackage(appInfo.packageName)
        if (intent != null){
            startActivity(intent)
        }
    }

}

class AppInfoWrapper(val appinfo: AppUtils.AppInfo) {
    override fun toString(): String {
        return appinfo.name
    }
}